<template>
  <div class="create-product-form">
    <form @submit.prevent="submitForm">
      <!-- 基本信息 -->
      <div class="form-section">
        <h3>基本信息</h3>
        <div class="form-grid">
          <div class="form-group">
            <label>商品名称 *</label>
            <input v-model="form.name" type="text" placeholder="请输入商品名称" required>
          </div>
          <div class="form-group">
            <label>商品编码 *</label>
            <input v-model="form.code" type="text" placeholder="请输入商品编码" required>
          </div>
          <div class="form-group">
            <label>关联商品 *</label>
            <select v-model="form.productId" required>
              <option value="">请选择基础商品</option>
              <option v-for="product in availableProducts" :key="product.id" :value="product.id">
                {{ product.productName }} - {{ product.spuCode }}
              </option>
            </select>
          </div>
          <div class="form-group">
            <label>关联SKU</label>
            <select v-model="form.skuId">
              <option value="">请选择SKU</option>
              <option v-for="sku in availableSkus" :key="sku.id" :value="sku.id">
                {{ sku.skuCode }} - {{ sku.attributes }}
              </option>
            </select>
          </div>
          <div class="form-group">
            <label>商品图片</label>
            <input type="file" @change="handleImageUpload" accept="image/*">
            <div v-if="form.imagePreview" class="image-preview">
              <img :src="form.imagePreview" alt="商品图片预览">
            </div>
          </div>
        </div>
      </div>

      <!-- 价格信息 -->
      <div class="form-section">
        <h3>价格信息</h3>
        <div class="form-grid">
          <div class="form-group">
            <label>零售价格 *</label>
            <input v-model.number="form.retailPrice" type="number" step="0.01" min="0" placeholder="请输入零售价格" required>
          </div>
          <div class="form-group">
            <label>会员价格</label>
            <input v-model.number="form.memberPrice" type="number" step="0.01" min="0" placeholder="请输入会员价格">
          </div>
          <div class="form-group">
            <label>成本价格</label>
            <input v-model.number="form.costPrice" type="number" step="0.01" min="0" placeholder="请输入成本价格">
          </div>
          <div class="form-group">
            <label>积分比例</label>
            <input v-model.number="form.pointsRatio" type="number" step="0.01" min="0" max="1" placeholder="积分比例（0-1）">
          </div>
        </div>
      </div>

      <!-- 库存信息 -->
      <div class="form-section">
        <h3>库存信息</h3>
        <div class="form-grid">
          <div class="form-group">
            <label>当前库存</label>
            <input v-model.number="form.stock" type="number" min="0" placeholder="请输入当前库存">
          </div>
          <div class="form-group">
            <label>最低库存</label>
            <input v-model.number="form.minStock" type="number" min="0" placeholder="请输入最低库存">
          </div>
          <div class="form-group">
            <label>最高库存</label>
            <input v-model.number="form.maxStock" type="number" min="0" placeholder="请输入最高库存">
          </div>
          <div class="form-group">
            <label>库存单位</label>
            <select v-model="form.stockUnit">
              <option value="件">件</option>
              <option value="台">台</option>
              <option value="套">套</option>
              <option value="盒">盒</option>
              <option value="包">包</option>
            </select>
          </div>
        </div>
      </div>

      <!-- 商品属性 -->
      <div class="form-section">
        <h3>商品属性</h3>
        <div class="form-grid">
          <div class="form-group">
            <label>是否序列化</label>
            <div class="checkbox-group">
              <label class="checkbox-item">
                <input v-model="form.isSerialized" type="checkbox">
                <span>是</span>
              </label>
            </div>
          </div>
          <div class="form-group">
            <label>是否赠品</label>
            <div class="checkbox-group">
              <label class="checkbox-item">
                <input v-model="form.isGift" type="checkbox">
                <span>是</span>
              </label>
            </div>
          </div>
          <div class="form-group">
            <label>商品状态</label>
            <select v-model="form.status">
              <option value="Active">启用</option>
              <option value="Inactive">禁用</option>
            </select>
          </div>
          <div class="form-group">
            <label>商品分类</label>
            <select v-model="form.categoryId">
              <option value="">请选择分类</option>
              <option v-for="category in categories" :key="category.id" :value="category.id">
                {{ category.name }}
              </option>
            </select>
          </div>
        </div>
      </div>

      <!-- 商品描述 -->
      <div class="form-section">
        <h3>商品描述</h3>
        <div class="form-grid">
          <div class="form-group full-width">
            <label>商品描述</label>
            <textarea v-model="form.description" placeholder="请输入商品描述" rows="4"></textarea>
          </div>
          <div class="form-group full-width">
            <label>商品规格</label>
            <textarea v-model="form.specifications" placeholder="请输入商品规格" rows="3"></textarea>
          </div>
        </div>
      </div>

      <!-- 操作按钮 -->
      <div class="form-actions">
        <button type="button" class="btn-cancel" @click="$emit('close')">
          取消
        </button>
        <button type="submit" class="btn-submit" :disabled="!isFormValid">
          <i class="fas fa-save"></i>
          创建商品
        </button>
      </div>
    </form>
  </div>
</template>

<script>
import { ref, computed, onMounted } from 'vue'

export default {
  name: 'CreateProductForm',
  emits: ['close', 'success'],
  setup(props, { emit }) {
    // 表单数据
    const form = ref({
      name: '',
      code: '',
      productId: '', // 添加 product_id 字段
      skuId: '',
      image: null,
      imagePreview: null,
      imageUrl: '', // 添加图片URL字段
      retailPrice: 0,
      memberPrice: 0,
      costPrice: 0,
      pointsRatio: 0.01,
      stock: 0,
      minStock: 0,
      maxStock: 0,
      stockUnit: '件',
      isSerialized: false,
      isGift: false,
      status: 'Active',
      categoryId: '',
      description: '',
      specifications: ''
    })
    
    // 可用商品列表
    const availableProducts = ref([])
    
    // 可用SKU列表
    const availableSkus = ref([
      {
        id: 1,
        skuCode: 'SKU-1001-RED-M',
        attributes: '红色 M码'
      },
      {
        id: 2,
        skuCode: 'SKU-1001-RED-L',
        attributes: '红色 L码'
      },
      {
        id: 3,
        skuCode: 'SKU-1002-BLUE-XL',
        attributes: '蓝色 XL码'
      }
    ])
    
    // 加载商品列表
    const loadProducts = async () => {
      try {
        // 首先尝试从基础商品API获取商品列表
        const response = await fetch('/api/commodity/products?size=100', {
          method: 'GET',
          headers: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${localStorage.getItem('token')}`
          }
        })
        
        if (response.ok) {
          const data = await response.json()
          availableProducts.value = data.content || []
        } else {
          console.error('加载基础商品列表失败:', response.statusText)
          // 如果基础商品API失败，尝试从零售商品API获取
          const retailResponse = await fetch('/api/retail/products?size=100', {
            method: 'GET',
            headers: {
              'Content-Type': 'application/json',
              'Authorization': `Bearer ${localStorage.getItem('token')}`
            }
          })
          
          if (retailResponse.ok) {
            const retailData = await retailResponse.json()
            // 从零售商品中提取基础商品信息
            const products = retailData.content || []
            const uniqueProducts = new Map()
            
            products.forEach(retailProduct => {
              if (retailProduct.productId && !uniqueProducts.has(retailProduct.productId)) {
                uniqueProducts.set(retailProduct.productId, {
                  id: retailProduct.productId,
                  productName: retailProduct.productName || `商品${retailProduct.productId}`,
                  spuCode: retailProduct.productCode || `PROD${retailProduct.productId}`
                })
              }
            })
            
            availableProducts.value = Array.from(uniqueProducts.values())
          } else {
            console.error('加载零售商品列表失败:', retailResponse.statusText)
            // 使用模拟数据
            availableProducts.value = [
              { id: 1, productName: 'iPhone 13', spuCode: 'IPHONE13' },
              { id: 2, productName: 'MacBook Pro', spuCode: 'MACBOOKPRO' },
              { id: 3, productName: 'Galaxy S22', spuCode: 'GALAXYS22' },
              { id: 4, productName: '男士衬衫', spuCode: 'SHIRT' },
              { id: 5, productName: '女士连衣裙', spuCode: 'DRESS' }
            ]
          }
        }
      } catch (error) {
        console.error('加载商品列表失败:', error)
        // 使用模拟数据
        availableProducts.value = [
          { id: 1, productName: 'iPhone 13', spuCode: 'IPHONE13' },
          { id: 2, productName: 'MacBook Pro', spuCode: 'MACBOOKPRO' },
          { id: 3, productName: 'Galaxy S22', spuCode: 'GALAXYS22' },
          { id: 4, productName: '男士衬衫', spuCode: 'SHIRT' },
          { id: 5, productName: '女士连衣裙', spuCode: 'DRESS' }
        ]
      }
    }
    
    // 商品分类
    const categories = ref([])
    
    // 加载商品分类
    const loadCategories = async () => {
      try {
        const response = await fetch('/api/commodity/categories?size=100', {
          method: 'GET',
          headers: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${localStorage.getItem('token')}`
          }
        })
        
        if (response.ok) {
          const data = await response.json()
          categories.value = data.content || []
        } else {
          console.error('加载商品分类失败:', response.statusText)
          // 使用模拟数据
          categories.value = [
            { id: 1, name: '电子产品' },
            { id: 2, name: '服装鞋帽' },
            { id: 3, name: '家居用品' },
            { id: 4, name: '食品饮料' }
          ]
        }
      } catch (error) {
        console.error('加载商品分类失败:', error)
        // 使用模拟数据
        categories.value = [
          { id: 1, name: '电子产品' },
          { id: 2, name: '服装鞋帽' },
          { id: 3, name: '家居用品' },
          { id: 4, name: '食品饮料' }
        ]
      }
    }
    
    // 处理图片上传
    const handleImageUpload = async (event) => {
      const file = event.target.files[0]
      if (file) {
        form.value.image = file
        const reader = new FileReader()
        reader.onload = (e) => {
          form.value.imagePreview = e.target.result
        }
        reader.readAsDataURL(file)
        
        // 上传图片到MinIO
        try {
          const formData = new FormData()
          formData.append('file', file)
          
          // 使用商品图片上传API，传入选中的商品ID
          const response = await fetch(`/api/retail/products/upload-image/${form.value.productId}`, {
            method: 'POST',
            headers: {
              'Authorization': `Bearer ${localStorage.getItem('token')}`
            },
            body: formData
          })
          
          if (response.ok) {
            const result = await response.json()
            form.value.imageUrl = result.fileUrl
            console.log('商品图片上传成功:', result.fileUrl)
          } else {
            console.error('图片上传失败:', response.statusText)
          }
        } catch (error) {
          console.error('图片上传失败:', error)
        }
      }
    }
    
    // 表单验证
    const isFormValid = computed(() => {
      return form.value.name && 
             form.value.code && 
             form.value.productId && // 添加 productId 验证
             form.value.retailPrice > 0
    })
    
    // 提交表单
    const submitForm = async () => {
      try {
        const productData = {
          ...form.value,
          giftPoints: Math.floor(form.value.retailPrice * form.value.pointsRatio),
          productImage: form.value.imageUrl // 使用 productImage 字段名
        }
        
        // 调用后端API创建商品
        const response = await fetch('/api/retail/products', {
          method: 'POST',
          headers: { 
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${localStorage.getItem('token')}`
          },
          body: JSON.stringify(productData)
        })
        
        if (response.ok) {
          console.log('商品创建成功')
          emit('success')
        } else {
          let errorMessage = response.statusText
          try {
            const errorData = await response.json()
            errorMessage = errorData.message || errorData.error || response.statusText
            console.error('创建商品失败:', errorData)
          } catch (parseError) {
            console.error('解析错误响应失败:', parseError)
            console.error('响应状态:', response.status, response.statusText)
          }
          alert(`创建商品失败: ${errorMessage}`)
        }
      } catch (error) {
        console.error('创建商品失败:', error)
        alert('创建商品失败，请检查网络连接')
      }
    }
    
    onMounted(() => {
      loadProducts()
      loadCategories()
    })
    
    return {
      form,
      availableProducts,
      availableSkus,
      categories,
      isFormValid,
      handleImageUpload,
      submitForm,
      loadProducts,
      loadCategories
    }
  }
}
</script>

<style scoped>
.create-product-form {
  max-width: 800px;
  margin: 0 auto;
}

.form-section {
  background: #f8fafc;
  border-radius: 8px;
  padding: 24px;
  margin-bottom: 24px;
}

.form-section h3 {
  font-size: 1.25rem;
  font-weight: 600;
  color: #2d3748;
  margin-bottom: 16px;
  padding-bottom: 8px;
  border-bottom: 2px solid #e2e8f0;
}

.form-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 16px;
}

.form-group {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.form-group.full-width {
  grid-column: 1 / -1;
}

.form-group label {
  font-weight: 500;
  color: #4a5568;
  font-size: 0.875rem;
}

.form-group input,
.form-group select,
.form-group textarea {
  padding: 10px 12px;
  border: 1px solid #e2e8f0;
  border-radius: 6px;
  font-size: 0.875rem;
  transition: border-color 0.3s ease;
}

.form-group input:focus,
.form-group select:focus,
.form-group textarea:focus {
  outline: none;
  border-color: #43e97b;
  box-shadow: 0 0 0 3px rgba(67, 233, 123, 0.1);
}

.form-group textarea {
  resize: vertical;
  min-height: 80px;
}

.image-preview {
  margin-top: 8px;
}

.image-preview img {
  width: 100px;
  height: 100px;
  object-fit: cover;
  border-radius: 6px;
  border: 1px solid #e2e8f0;
}

.checkbox-group {
  display: flex;
  gap: 16px;
}

.checkbox-item {
  display: flex;
  align-items: center;
  gap: 8px;
  cursor: pointer;
}

.checkbox-item input[type="checkbox"] {
  width: 18px;
  height: 18px;
  margin: 0;
}

.form-actions {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  padding: 24px 0;
}

.btn-cancel,
.btn-submit {
  padding: 12px 24px;
  border: none;
  border-radius: 6px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;
}

.btn-cancel {
  background: #e2e8f0;
  color: #4a5568;
}

.btn-submit {
  background: #43e97b;
  color: white;
  display: flex;
  align-items: center;
  gap: 8px;
}

.btn-submit:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.btn-cancel:hover,
.btn-submit:hover:not(:disabled) {
  transform: translateY(-1px);
}

@media (max-width: 768px) {
  .form-grid {
    grid-template-columns: 1fr;
  }
  
  .form-actions {
    flex-direction: column;
  }
}
</style>
